import mongoose = require('mongoose');
import q = require('bluebird');
mongoose.Promise = q;

import fs = require("fs");
import WebConstant from '../common/WebConstant';
import CommonFunc from '../middleware/CommonFunc';
import FileListProvider from './FileListProvider';

export default class AdminLogicClass extends FileListProvider {
    private pageItemCount:number = 30;
    public index(req:any){
        let query = req.query;
        let extraPath:string = query.path || "";
        if(extraPath.length > 0 && !extraPath.endsWith("/")){
            extraPath += "/";
        }
        let page = query.page || 1;
        let skip = (page - 1) * this.pageItemCount;
        let limit = this.pageItemCount;
        let me = this;
        let currentUser = req.session && req.session.user && req.session.user.username;
         
        let defaultPath = CommonFunc.getRootUserPath(currentUser);
        extraPath = extraPath.replace(defaultPath, "");
        //console.log("userpath =", userPath, "  | extraPath=", extraPath);
        let promise = new q((resolve,reject)=>{
            fs.readdir(defaultPath + extraPath, (err: NodeJS.ErrnoException, files: string[]) =>{
                let dataResult = me.getFilelistUnderPath(defaultPath, extraPath, files, me.pageItemCount, skip, ["temp"]);
                let count = dataResult.count;
                let total = Math.ceil(count / limit);
                let result:{[key:string]:any} = {};
                result['data'] =  dataResult.data;
                result['pager'] = {"total":total,"current":page, "datacount":count};
                result['param'] = {"pathlist":me.makePathList(defaultPath, extraPath),"extrapath":extraPath};
                resolve(result);
            });
        });

        return promise;
    }
    public uploadfile(req:any){
        let currentUser = req.session && req.session.user && req.session.user.username;
        let userPath = currentUser + "/";

        let defaultPath = WebConstant.UPLOAD_PATH + userPath;
        let me = this;
        let promise = new q((resolve,reject)=>{
            let allfiles:string[] = [];
            try{
                me.recursionFolder(defaultPath, allfiles);
            }
            catch(ex){
                console.log("[Error]",ex.message);
            }
            let dataResult = me.getFolderList(defaultPath,  allfiles);
            let result:{[key:string]:any} = {};
            result['data'] =  dataResult;
            result['pager'] = {"total":0,"current":1, "datacount":0};
            result['param'] = {};
            resolve(result);
        });

        return promise;
    }
    
    
    private makePathList(defaultPath:string, extraPath:string, lastlevel?:string):any[]{
        if(!extraPath || extraPath.length <= 0){
            return [];
        }
        if(!lastlevel){
            lastlevel = defaultPath;
        }
        let finalList = [];
        let pathlist = extraPath.split("/");
        for(let i = 0; i < pathlist.length; i++){
            if(pathlist[i].length <= 0){
                continue;
            }
            let shortPath = this.shortPath(defaultPath, lastlevel+pathlist[i]);
            finalList.push({"name":pathlist[i],"path":shortPath});
            lastlevel += pathlist[i] + "/";
        }
        return finalList;
    }
    private getFolderList(defaultPath:string, files:string[]):string[]{
        if(!files || files.length <= 0){
            return [];  
        }       
        let retList = [];
        for(let i = 0; i < files.length; i++){
            try{
                let stats = fs.lstatSync(files[i]);
                let isFolder = stats.isDirectory();
                if(!isFolder){
                    continue;
                }
                let shortPath = this.shortPath(defaultPath, files[i]);
                retList.push(shortPath);
            }
            catch(ex){
                console.log(ex.message);
            }
        }
        return retList;
    }
    private recursionFolder(path:string, allfiles:string[]):void{
        let me = this;
        let files = fs.readdirSync(path);
        if(!files || files.length <= 0){
            return;
        }    
        for(let i = 0; i < files.length; i++){
            if(files[i].startsWith(".")){
                continue;
            }
            
    
            try{
                let stats = fs.lstatSync(path+""+files[i]);
                let isFolder = stats.isDirectory();
                if(!isFolder){
                    continue;
                }
                if(files[i] == "temp"){
                    continue;
                }
                
                allfiles.push(path+files[i]);
                me.recursionFolder(path+files[i]+"/", allfiles);
            }
            catch(ex){
                console.log(ex.message);
            }
        }
    }
}
